import { reactive, ref, computed, onMounted } from "vue";
import { flow } from "lodash";
import {
  getNamespaceMergeData,
  buildApiData,
  getIpPortMergeData,
  getNoMergeTopoData,
} from "./topoService";
import { useRoute } from "vue-router";

import dayjs from "dayjs";
import request from "@/utils/request";
import { nodePosition, topoGraph } from "@/api/topo";
export default function useTopology({
  groupValue,
  mode,
  attachDataType,
  isMerge,
  timeInfo,
}) {
  const route = useRoute();
  const editTopoData = ref({ nodes: [], edges: [] });
  const topoData = ref({ nodes: [], edges: [] });
  const topoNodesToSearch = computed(() => {
    return mode === "edit" ? editTopoData.value.nodes : topoData.value.nodes;
  });
  const topoDataUserPos = ref([]);
  function getTopoData() {
    const { diff } = timeInfo;
    const { systemId, type } = route.query;
    const params = {
      systemId,
      type,
      ...timeInfo,
    };

    // const nodes, edges
    // this.topoQueryTime = timeInfo;
    // this.setState({ queryTime: { from, to } })

    const posParams = {
      systemId,
    };
    //首先请求现有位置，储存
    nodePosition(posParams)
      .then((res) => {

        if (res.data?.length > 0) {
          const nodeListHasPosByUser = res.data;
          topoDataUserPos.value = nodeListHasPosByUser;
        }
      });

      topoGraph(params).then((res) => {
      const { instances: apiNodes, edges: apiEdges } = res.data;
      const { nodes, edges } = buildApiData(
        apiNodes,
        apiEdges,
        diff,
        attachDataType
      );

      const getTopoDataFn = flow([
        changeTopoDataByUserPos,
        getTopoDataByIsMerge,
      ]);

      topoData.value = getTopoDataFn({ nodes, edges });
    });
  }

  function changeTopoDataByUserPos(topoData) {
    const userData = topoDataUserPos.value;

    // const { groupValue } = this.state;
    let targetTopoData = userData.filter((group) => {
      return (
        group.groupType ==
        (groupValue == "none"
          ? 0
          : groupValue == "namespace"
          ? 1
          : groupValue == "merge" && 2)
      );
    })[0]?.nodePos;
    !targetTopoData && (targetTopoData = new Array());
    // console.log('目标拓扑', topoData);

    const nodePosMap = new Map();
    if (targetTopoData.length > 0) {
      targetTopoData.forEach((item) => {
        nodePosMap.set(item.nodeKey, { xaxis: item.xaxis, yaxis: item.yaxis });
      });
      topoData.nodes.forEach((item) => {
        if (nodePosMap.get(item.workloadKey)) {
          ({ xaxis: item.xaxis, yaxis: item.yaxis } = nodePosMap.get(
            item.workloadKey
          ));
        }
      });
      // groupValue !=='none'&& topoData?.combos.forEach(item=>{
      //     ({xaxis:item.xaxis, yaxis:item.yaxis} = nodePosMap.get(item.workloadKey))
      // });
    }
    // console.log('修改后', topoData);
    return topoData;
  }
  // 根据归并方式生成拓扑数据
  function getTopoDataByIsMerge(topoData) {
    // const { isMerge } = this.state;
    let newTopoData;
    const handlers = {
      namespace: flow([getNamespaceMergeData, changeTopoDataByUserPos]),
      merge: flow([getIpPortMergeData, changeTopoDataByUserPos]),
      none: flow([getNoMergeTopoData, changeTopoDataByUserPos]),
      _default: flow([getNoMergeTopoData, changeTopoDataByUserPos]),
    };

    newTopoData = handlers[groupValue.value || "_default"]?.(topoData);

    return newTopoData;
  }
  // 搜索节点
  function onSearchNode(value) {
    let ref;
    if (mode === "edit") {
      ref = this.editTopoRef;
    } else if (mode === "merge") {
      ref = this.mergeTopoRef;
    } else {
      ref = this.topoRef;
    }

    if (!ref?.current?.graph) {
      return;
    }
    const graph = ref.current.graph;
    // 清除所有节点状态
    if (!value) {
      clearAllStats(graph);
      return;
    }
    if (value) {
      const nodes = editMode === "edit" ? editTopoData.value.nodes : topoData.value.nodes;
      const searchNode = find(nodes, { id: value });
      clearAllStats(graph);
      if (searchNode?.comboId) {
        const comboItem = graph.findById(searchNode.comboId);
        const comboModel = comboItem.getModel();
        // 若搜索的点在combo里，则展开combo
        if (comboItem && comboModel.collapsed) {
          comboItem._xxx = true;
          graph.expandCombo(comboItem);
        }
      }
      const searchNodeItem = graph.findById(searchNode?.id);
      graphFocusNode(searchNodeItem, graph, true);
      graph.setItemState(searchNodeItem, "hover", true);
    }
  }
  return {
    topoNodesToSearch,
    topoData,
    topoDataUserPos,
    editTopoData,
    getTopoData,
    getTopoDataByIsMerge,
    changeTopoDataByUserPos,
  };
}
